package cn.yunyichina.provider.sys.service.impl;

import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.sys.dao.DeptUserRelationDao;
import cn.yunyichina.provider.sys.dao.OrgUserDao;
import cn.yunyichina.provider.sys.dao.UserRoleRelationDao;
import cn.yunyichina.provider.sys.entity.DeptUserRelation;
import cn.yunyichina.provider.sys.entity.OrgUser;
import cn.yunyichina.provider.sys.entity.UserRoleRelation;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.StringUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.security.MD5Util;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by 15-AK on 2018/2/1.
 */
@Service
public class AccountServiceImpl {
    private static Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);

    @Autowired
    private OrgUserDao orgUserDao;
    @Autowired
    private DeptUserRelationDao deptUserRelationDao;
    @Autowired
    private UserRoleRelationDao userRoleRelationDao;

    /**
     * yyt.sys.account.save
     * 新增账号
     *
     * @param data
     * @return
     * @throws CallException
     */
    @Transactional
    public Response saveAccount(String data) throws CallException {
        Response response = new Response();
        try {
            logger.info("savaAccount原始入参data={}", data);
            OrgUser requestVo = JsonUtils.parseObject(data, OrgUser.class);
            DeptUserRelation deptUserRelation = JsonUtils.parseObject(data, DeptUserRelation.class);
            JSONObject jsonObject = JSON.parseObject(data);

            if (StringUtils.isBlank(requestVo.getLoginName()) || StringUtils.isBlank(requestVo.getUserName())
                    || StringUtils.isBlank(requestVo.getPassword()) || StringUtils.isBlank(requestVo.getMobile())
                    || StringUtils.isBlank(deptUserRelation.getOrgId()) || StringUtils.isBlank(deptUserRelation.getDeptId())) {
                response.setResultCodeAndMessage("1101", "参数缺失请校验");
                return response;
            }

            OrgUser queryOrgUser = new OrgUser();
            queryOrgUser.setLoginName(requestVo.getLoginName());
            List<OrgUser> orgUserList = orgUserDao.select(queryOrgUser);

            requestVo.setSalt("123456");
            requestVo.setPassword(MD5Util.string2MD5(MD5Util.string2MD5(requestVo.getPassword()) + requestVo.getSalt()));

            if(StringUtils.isBlank(requestVo.getBirth())){
                requestVo.setBirth(null);
            }
            if (CollectionUtils.isEmpty(orgUserList)) {
                requestVo.setId(PKGenerator.generateId());
                requestVo.setCreatedTime(DateUtils.dateToString(new Date()));
                requestVo.setUpdateTime(DateUtils.dateToString(new Date()));
                orgUserDao.insert(requestVo);
            } else {
                //更新
                requestVo.setId(orgUserList.get(0).getId());
                requestVo.setUpdateTime(DateUtils.dateToString(new Date()));
                orgUserDao.update(requestVo);
            }

            DeptUserRelation queryDeptUserRelation = new DeptUserRelation();
            queryDeptUserRelation.setUserId(requestVo.getId());
            List<DeptUserRelation> deptUserRelations = deptUserRelationDao.select(queryDeptUserRelation);
            if (!CollectionUtils.isEmpty(deptUserRelations)) {
                deptUserRelationDao.delete(deptUserRelations.get(0));
            }

            deptUserRelation.setId(PKGenerator.generateId());
            deptUserRelation.setUserId(requestVo.getId());
            deptUserRelation.setUserName(requestVo.getUserName());
            deptUserRelation.setLoginName(requestVo.getLoginName());
            deptUserRelation.setEnableFlag(new Short("1"));
            deptUserRelationDao.insert(deptUserRelation);

            if (!CollectionUtils.isEmpty(deptUserRelations)) {
                UserRoleRelation deleteUserRoleRelation = new UserRoleRelation();
                deleteUserRoleRelation.setDeptUserRelationId(deptUserRelations.get(0).getId());
                userRoleRelationDao.deleteByDeptUserRelationId(deleteUserRoleRelation);
            }

            String roleIdList = jsonObject.getString("role_id_list");
            if (!StringUtils.isBlank(roleIdList)) {
                List<String> roleIds = Arrays.asList(roleIdList.split(","));
                if (CollectionUtils.isNotEmpty(roleIds)) {
                    List<UserRoleRelation> userRoleRelations = new ArrayList<>();
                    for (String roleId : roleIds) {
                        UserRoleRelation userRoleRelation = new UserRoleRelation();
                        userRoleRelation.setId(PKGenerator.generateId());
                        userRoleRelation.setDeptUserRelationId(deptUserRelation.getId());
                        userRoleRelation.setRoleId(roleId);
                        userRoleRelations.add(userRoleRelation);
                    }
                    userRoleRelationDao.batchInsert(userRoleRelations);
                }
            }

            response.setResultCodeAndMessage("0", "账号保存成功");
        } catch (CallException e) {
            throw new CallException("-1", "账号保存失败" + e.getMessage());
        }
        return response;
    }

    /**
     * yyt.sys.account.list
     *
     * @param data
     * @return
     */
    public Response listAccount(String data) {
        logger.info("listAccount原始入参data={}", data);
        Response response = new Response();
        OrgUser wheres = JsonUtils.parseObject(data, OrgUser.class);
        PageInfo pageInfo = JsonUtils.parseObject(data, PageInfo.class);
        wheres.setEnableFlag(new Short("1"));
        if (pageInfo != null) {
            List<String> orderColumns = new ArrayList<>();
            orderColumns.add("CREATED_TIME");
            List<OrgUser> orgUserList = orgUserDao.select(wheres, orderColumns, false, pageInfo);

            Map<String, Object> resultMap = new HashMap<>();

            Long dataCount = orgUserDao.selectCount(wheres);
            pageInfo.setTotal(dataCount);
            pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
            resultMap.put("page_info", pageInfo);
            resultMap.put("list", orgUserList);
            response.setResultCodeAndMessageAndResult("0", "成功", JsonUtils.toJsonString(resultMap));
        } else {
            List<OrgUser> orgUserList = orgUserDao.select(wheres);
            response.setResultCodeAndMessageAndResult("0", "成功", JsonUtils.toJsonString(orgUserList));
        }
        logger.info("listAccount 出参response={}", new Object[]{JsonUtils.toJsonString(response)});
        return response;
    }

    /**
     * yyt.sys.account.delete
     * 删除账号
     *
     * @param data
     * @return
     */
    public Response deleteAccount(String data) {
        logger.info("deleteAccount原始入参data={}", data);
        Response response = new Response();
        OrgUser request = JsonUtils.parseObject(data, OrgUser.class);
        if (StringUtils.isBlank(request.getId())) {
            response.setResultCodeAndMessage("1101", "id参数缺失");
        }
        OrgUser orgUser = orgUserDao.selectById(request.getId());
        if (orgUser == null) {
            response.setResultCodeAndMessage("1101", "账号不存在");
        }

        orgUserDao.delete(orgUser);
        DeptUserRelation deptUserRelation = new DeptUserRelation();
        deptUserRelation.setUserId(orgUser.getId());
        List<DeptUserRelation> deptUserRelations = deptUserRelationDao.select(deptUserRelation);
        if (CollectionUtils.isNotEmpty(deptUserRelations)){
            UserRoleRelation userRoleRelation = new UserRoleRelation();
            userRoleRelation.setDeptUserRelationId(deptUserRelations.get(0).getId());
            userRoleRelationDao.deleteByDeptUserRelationId(userRoleRelation);
            deptUserRelationDao.deleteByUserId(deptUserRelation);

        }


        response.setResultCodeAndMessage("0", "删除账号成功");
        return response;
    }

    /**
     * 获取部门下的账户
     * yyt.sys.account.by.dept.list
     *
     * @param data
     * @return
     */
    public Response listAccountByDept(String data) {
        logger.info("listAccountByDept原始入参data={}", data);
        Response response = new Response();
        DeptUserRelation wheres = JsonUtils.parseObject(data, DeptUserRelation.class);
        wheres.setEnableFlag(new Short("1"));

        PageInfo pageInfo = JsonUtils.parseObject(data, PageInfo.class);
        if(pageInfo ==null || pageInfo.getPageSize() ==null ||pageInfo.getPageNum() ==null){
            response.setResultCodeAndMessage("1001","分页参数缺失");
            return response;
        }

        if (pageInfo != null) {
            List<OrgUser> orgUserList = deptUserRelationDao.listAccountByDept(wheres, pageInfo);
            Map<String, Object> resultMap = new HashMap<>();

            Long dataCount = deptUserRelationDao.selectCountAccountByDept(wheres);
            pageInfo.setTotal(dataCount);
            pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
            resultMap.put("page_info", pageInfo);
            resultMap.put("list", orgUserList);
            response.setResultCodeAndMessageAndResult("0", "成功", JsonUtils.toJsonString(resultMap));
        }

        return response;

    }

    /**
     * 查找账号已分配的角色
     * @param userId
     * @return
     */
    public List<UserRoleRelation> ListUserRoleByUserId(String userId){
        DeptUserRelation queryDeptUserRelation = new DeptUserRelation();
        queryDeptUserRelation.setUserId(userId);
        List<DeptUserRelation> deptUserRelations = deptUserRelationDao.select(queryDeptUserRelation);
        if (CollectionUtils.isEmpty(deptUserRelations)) {
            return null;
        }
        UserRoleRelation userRoleRelation = new UserRoleRelation();
        userRoleRelation.setDeptUserRelationId(deptUserRelations.get(0).getId());

        List<UserRoleRelation> list = userRoleRelationDao.select(userRoleRelation);
        return list;
    }

}
